#!/usr/bin/python
# -*- coding: utf-8 -*-  

import pygame
from pygame.locals import *
import constante as cons
import time

import chip8

class PygameEngine(chip8.TemplateGraphicEngine):
	def __init__(self):
		self.initialize_engine()
		chip8.TemplateGraphicEngine.__init__(self)
		self.draw(	clear=lambda: self.stdscr.fill(pygame.Color('black')),
					refresh = pygame.display.flip,
					draw_BLACK = 	lambda x, y: pygame.draw.rect(self.stdscr, 
									pygame.Color('black'),
									(x*cons.PIXEL_SIZE, y*cons.PIXEL_SIZE, cons.PIXEL_SIZE, cons.PIXEL_SIZE)),
					draw_WHITE = 	lambda x, y: pygame.draw.rect(self.stdscr, 
									pygame.Color('white'),
									(x*cons.PIXEL_SIZE, y*cons.PIXEL_SIZE, cons.PIXEL_SIZE, cons.PIXEL_SIZE)),
					bind_key = self.bind_input)
	
	def initialize_engine(self):
		pygame.init()
		self.stdscr = pygame.display.set_mode((cons.SCR_WIDTH*cons.PIXEL_SIZE, cons.SCR_HEIGHT*cons.PIXEL_SIZE),pygame.DOUBLEBUF)
		self.keyboard = (K_o, K_w, K_x, K_c, K_q, K_s, K_d, K_a, K_z, K_e, K_i, K_p, K_k, K_l, K_m)
	
	def bind_input(self):
		for event in pygame.event.get():
			if (event.type == QUIT) or (event.type == KEYDOWN and (event.key == K_ESCAPE or event.key == K_n)):
				cons.IS_RUNNING = False
			if event.type == KEYDOWN and event.key in self.keyboard:
				ind = self.keyboard.index(event.key)
				self.bus_input[ind] = 1
			elif event.type == KEYUP and event.key in self.keyboard:
				ind = self.keyboard.index(event.key)
				self.bus_input[ind] = 0

if __name__ == "__main__":
	import sys
	cons.ROM = sys.argv[1]
	PygameEngine()